"""
    Created by 范钟<coder.zf@outlook.com> on 2019/04/06
"""


class BookViewModel:
    def __init__(self, book):
        self.title = book['title']
        self.publisher = book['publisher']
        self.pages = book['pages'] or ''
        self.author = "、".join(book['author'])
        self.price = book['price'] or ''
        self.summary = book['summary'] or ''
        self.image = book['image']
        self.isbn = book['isbn']

    @property
    def intro(self):
        intros = filter(lambda x: True if x else False, [self.author, self.publisher, self.price])
        return " / ".join(intros)


class BookCollection:
    def __init__(self):
        self.total = 0
        self.keyword = ''
        self.books = []

    def fill(self, yushu_book, keyword):
        self.total = yushu_book.total
        self.books = [BookViewModel(book) for book in yushu_book.books]
        self.keyword = keyword


class _BookViewModel:
    @classmethod
    def package_single(cls, data, keyword):
        returned = {
            'books': [],
            'total': 0,
            'keyword': keyword
        }
        if not data:
            return returned

        returned['books'].append(cls.__cut_book_data(data))
        returned['total'] = 1

        return returned

    @classmethod
    def package_collection(cls, data, keyword):
        returned = {
            'book': [cls.__cut_book_data(book) for book in data['books']],
            'total': data['total'],
            'keyword': keyword
        }
        return returned

    @classmethod
    def __cut_book_data(cls, data):
        book = {
            'title': data['title'],
            'publisher': data['publisher'],
            'pages': data['pages'] or '',
            'author': "、".join(data['author']),
            'price': data['price'] or '',
            'summary': data['summary'] or '',
            'image': data['image']
        }
        return book
